<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;


/**
 *
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class AlipayController extends AdminController
{


    /**
     *口碑商户等待审核列表
     */
    public function handle_index()
    {


        $list = D('Kbsh')->where(['status' => 3])->select();
        foreach ($list as $key => $value) {
            $user_id = $value['user_id'];
            $app_auth_code = $value['app_auth_code'];
            $name = $value['name'];

            // 删除没有名字的
            if (empty($name)) {
                D('Kbsh')->where("id=$value[id]")->delete();
            }

            // 删除code重复的、未审核的、名字存在 剩下一条
            $one2 = D('Kbsh')->where(['app_auth_code' => $app_auth_code, 'status' => 0])->select();
            if (count($one2) > 1) {
                unset($one2[0]);
                foreach ($one2 as $key => $v) {
                    D('Kbsh')->where("id=$v[id]")->delete();
                }
            }


            // 删除重复user_id 只剩一条
            $one1 = D('Kbsh')->where(['user_id' => $user_id, 'status' => 1])->order('id desc')->select();

            if (count($one1) > 1) {
                unset($one1[0]);
                print_r($one1);
                foreach ($one1 as $key => $va) {
                    D('Kbsh')->where("id=$va[id]")->delete();
                }
            }

        }
        $where = array();
        $title = I('get.title');
        if (strlen($title) == 16) {
            $where['user_id'] = $title;
        } else {
            $where['name'] = array('like', "%{$title}%");
        }
        $list = $this->lists('Kbsh', $where);
        if (empty($list)) {
            $one = D('Kbxx')->where(['name' => array('like', "%{$title}%")])->find();
            $list = $this->lists('Kbsh', ['uid' => $one['uid']]);
        }

        $today = date('Ymd');

        foreach($list as $k => $v){
            $todayDingdan = M('dingdan')->query("SELECT sum(pay_money) as money FROM jd_dingdan WHERE seller_id=".$v['user_id']." and  FROM_UNIXTIME(createtime, '%Y%m%d')=$today");
            $list[$k]['todayAccount'] = $todayDingdan ? $todayDingdan[0]['money'] : 0;
        }


        $this->assign('_list', $list);
        $this->meta_title = '口碑商户';
        $this->display();


    }

    /**
     *口碑商户在线商户列表
     */
    public function index()
    {


//        $list = D('Kbsh')->where(['status' => ['neq',3]])->select();
        $list = D('Kbsh')->select();
        foreach ($list as $key => $value) {
            $user_id = $value['user_id'];
            $app_auth_code = $value['app_auth_code'];
            $name = $value['name'];

            // 删除没有名字的
            if (empty($name)) {
                D('Kbsh')->where("id=$value[id]")->delete();
            }

            // 删除code重复的、未审核的、名字存在 剩下一条
            $one2 = D('Kbsh')->where(['app_auth_code' => $app_auth_code, 'status' => 0])->select();
            if (count($one2) > 1) {
                unset($one2[0]);
                foreach ($one2 as $key => $v) {
                    D('Kbsh')->where("id=$v[id]")->delete();
                }
            }


            // 删除重复user_id 只剩一条
            $one1 = D('Kbsh')->where(['user_id' => $user_id, 'status' => 1])->order('id desc')->select();

            if (count($one1) > 1) {
                unset($one1[0]);
                print_r($one1);
                foreach ($one1 as $key => $va) {
                    D('Kbsh')->where("id=$va[id]")->delete();
                }
            }

            //获取经营数据
            $jingying = \Home\Logic\ShopLogic::getJingYing($value['id']);
            $list[$key]['jinRiDingDan'] = $jingying['jinRiDingDan'];//今日订单数
            $list[$key]['jinRiChengGong'] = $jingying['jinRiChengGong'];//今日成功订单数
            $list[$key]['jinRiChengGongLv'] = $jingying['jinRiChengGongLv'];//今日成功率


        }
        $where = array();
        $title = I('get.title');
        if (strlen($title) == 16) {
            $where['user_id'] = $title;
        } else {
            $where['name'] = array('like', "%{$title}%");
        }
        $list = $this->lists('Kbsh', $where);
        if (empty($list)) {
            $one = D('Kbxx')->where(['name' => array('like', "%{$title}%")])->find();
            $list = $this->lists('Kbsh', ['uid' => $one['uid']]);
        }

        $today = date('Ymd');

        foreach($list as $k => $v){
            $todayDingdan = M('dingdan')->query("SELECT sum(pay_money) as money FROM jd_dingdan WHERE seller_id=".$v['user_id']." and  FROM_UNIXTIME(createtime, '%Y%m%d')=$today");
            $list[$k]['todayAccount'] = $todayDingdan ? $todayDingdan[0]['money'] : 0;
        }


        $this->assign('_list', $list);
        $this->meta_title = '口碑商户';
        $this->display();


    }
    /**
     * 商户信息
     */
    public function kbxx()
    {

        if (IS_POST) {
            $uid = I('post.uid');
            $id = D('Kballow')->add(['uid' => $uid]);
            print_r($id);
            die;
        } else {
            $list = $this->lists('Kbxx');
            $this->assign('_list', $list);
            $this->meta_title = '商户信息';
            $this->display();
        }
    }

    /**
     * 口碑商户信息
     * 设置授权
     */
    public function koubei_view()
    {

        if (IS_POST) {
            $status = $_POST['real_status'];
            if ($status == 0) {
                $id = D('Kbxx')->where('uid=' . $_POST['uid'])->save(['real_status' => 0]);
                D('Kballow')->where(['uid' => $_POST['uid']])->delete();
            } else {
                $id = D('Kbxx')->where('uid=' . $_POST['uid'])->save(['real_status' => 1, 'money' => $_POST['money']]);
                D('Kbsh')->where('uid=' . $_POST['uid'])->save(['rate' => $_POST['rate']]);
            }

            if ($id > 0) {
                echo "操作成功！";
                die;
            } else {
                echo "操作失败！";
                die;
            }
        } else {
            $id = $_GET['id'];
            $list = D('Kbxx')->where("id={$id}")->find();
            $kb_list = D('Kbsh')->where('uid=' . $list['uid'])->select();

            $this->assign('_list', $list);
            $this->assign('list', $kb_list);
            // print_r($list);die;
            $this->meta_title = '商户信息';
            $this->display();
        }


    }

    public function kb_dingdan()
    {

        if (IS_POST) {

        } else {
            $id = $_GET['id'];
            $type = I('get.type');
            $map = array();
            $order = 'pay_time desc';
            $map['seller_id'] = $id;
            if ($type == 'today') {
                $time1 = strtotime(date("Ymd"));
                $time2 = strtotime(date("Ymd", time() + 86400));
                $map['pay_time'] = array(array('gt', $time1), array('lt', $time2), 'and');
                $map['status'] = 1;
            } elseif ($type == 'success') {

                $map['status'] = array('eq', 1);

            } elseif ($type == 'fail') {

                $map['status'] = array('eq', 0);

            }

            $list = $this->lists('Dingdan', $map, $order);
            $this->assign('_list', $list);
            $this->assign('id', $id);


            $money = D('Dingdan')->where(['status' => 1, 'seller_id' => $id])->sum('pay_money');
            $this->assign('money', $money);


            $time1 = strtotime(date("Ymd", strtotime("+1 day")));
            $time2 = strtotime(date("Ymd"));
            $sum['td_in'] = D('Dingdan')->where("status=1 and seller_id='$id' and pay_time between $time2 and $time1")->sum('pay_money');

            $sum['t_money'] = D('Dingdan')->where("status=1 and seller_id='$id'")->sum('pay_money');

            $this->assign('sum', $sum);


            // print_r($list);die;
            $this->meta_title = '订单列表';
            $this->display();
        }
    }

    // 解除口碑授权
    public function shouquan()
    {
        $type = I('post.type');
        $_type = I('post._type');
        $app_auth_code = I('post.app_auth_code');
        if (empty($app_auth_code)) {
            echo '条件不可空！';
            die;
        } else {

            if (!empty($_type)) {

                $id = D('Kbsh')->where("app_auth_code='$app_auth_code'")->save(['type' => $_type]);
                echo $id;
                die;
            } else if ($type == 1) {
                $id = D('Kbsh')->where("app_auth_code='$app_auth_code'")->delete();
            } else {
                if ($type == 2) {
                    $id = D('Kbsh')->where("app_auth_code='$app_auth_code'")->save(['use_status' => 1, 'cause' => '']);
                } else {
                    $id = D('Kbsh')->where("app_auth_code='$app_auth_code'")->save(['use_status' => 0, 'cause' => '手动下架']);
                }
            }

            // echo D('Kbsh')->getlastsql();die;
            if ($id > 0) {
                echo 1;
                die;
            } else {
                echo 0;
                die;
            }
        }

    }

    // 获取授权令牌
    public function get_token()
    {
        $code = $_GET['code'];
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $transfer = new \Alipay;
//        $adata = D('Adata')->where(['id' => 1])->find();
        $adata = M('shouquan')->find();

        $result = $transfer->get_token($code, $adata);


        if ($result->code == '10000') {

            $user_id = $result->user_id;
            $one = D('Kbsh')->where(['user_id' => $user_id])->select();
            if (!empty($one)) {  //之前存在 则删除
                D('Kbsh')->where(['user_id' => $user_id])->delete();
            }
            $data = [
                'app_auth_token' => $result->app_auth_token,
                'app_refresh_token' => $result->app_refresh_token,
                'auth_app_id' => $result->auth_app_id,
                'user_id' => $result->user_id,
                'expires_in' => 31536000,
                're_expires_in' => 32140800,
                'create_time' => $create_time,
                'status' => 1,
            ];
            $trl = D('Kbsh')->where("app_auth_code='{$code}'")->save($data);
            $this->redirect('view');
        } else {
            // echo "<script>alert('".$result->sub_msg."');history.go(-1)</script>";die;
            $this->error($result->sub_msg, U('Alipay/view'));
        }


    }

// 口碑商户详情
    public function view()
    {
        $id = I('get.id');

        if (IS_POST) {
//            status:测试状态:0=未测试,1=正常,2=异常
//            use_status:使用状态:0=离线,1=在线


            $data = I('post.');
            $oldkbsh = M('kbsh')->find($id);
            if($data['use_status'] == 1 && $oldkbsh['use_status'] != 1){
                \Home\Logic\ShopLogic::addRedisShop(2,$id);
            }else{
                \Home\Logic\ShopLogic::delRedisShop(2,$id);

            }

//            if($data['status'] == 1){
//                \Home\Logic\ShopLogic::addRedisShop(2,$id);
//
//            }else{
//                \Home\Logic\ShopLogic::delRedisShop(2,$id);
//
//            }


            $res = M('kbsh')->where(['id' => $id])->save($data);
            if($res !== false){
                echo "修改成功";die;
            }else{
                echo "修改失败";die;
            }

        } else {


            $id = I('get.id');
            $info = D('Kbsh')->where("id=" . $id)->find();
            $uid = $info['uid'];
            $one = D('Kbsh')->where(['status' => 1, 'uid' => $uid])->find();
            if (empty($one)) {

            } else {
                D('Kbsh')->where("id=" . $id)->save(['rate' => $one['rate']]);
            }

            $info = D('Kbsh')->where("id=" . $id)->find();

            $list = D('Kbxx')->where("uid={$info['uid']}")->find();

            //总金额
            $dingdan = D('Dingdan')->where(['status' => 1, 'seller_id' => $info['user_id']])->select();
            $money = 0.00;
            foreach ($dingdan as $v) {
                $money = $money + $v['pay_money'];
            }
            //今日交易额
            $time1 = strtotime(date("Ymd"));
            $time2 = strtotime(date("Ymd")) + 86400;
            $dingdan = D('Dingdan')->where("status=1 and `seller_id`='$info[user_id]' and `pay_time` between '$time1' and '$time2'")->select();
            $todaymoney = 0.00;
            foreach ($dingdan as $v) {
                $todaymoney = $todaymoney + $v['pay_money'];
            }

            $info['total_money'] = $money;
            $info['today_money'] = $todaymoney;

            $this->assign('_list', $info);

            $this->meta_title = '口碑商户详情';
            $this->display();
        }

    }


// 平台商户详情
    public function yh_view()
    {

        if (IS_POST) {
//            dump($_POST);exit;
            $uid = $_POST['uid'];

            $data1 = [
                'name' => $_POST['name'],
                'alipay' => $_POST['alipay'],
//                'password' =>md5($_POST['password'])
            ];

            $data2 = [
                'path1' => $_POST['path1'],
                'path2' => $_POST['path2'],
                'path3' => $_POST['path3'],
                'path4' => $_POST['path4'],
                'up_set' => $_POST['up_set'],
                'up_set2' => $_POST['up_set2'],

                'status' => $_POST['status'],
                'status_xy' => $_POST['status_xy'],
                'status_hb' => $_POST['status_hb'],
                'status_fq' => $_POST['status_fq'],
                'status_tm' => $_POST['status_tm'],
            ];
            $id1 = D('Ptyh')->where('uid=' . $uid)->save($data1);
            $id2 = D('Gather')->where('uid=' . $uid)->save($data2);
            if ($id2 > 0 || $id1 > 0) {
                $yh = D('Ptyh')->where("uid=" . $uid)->find();
                $gather = D('Gather')->where("uid=" . $uid)->find();
                $this->assign('yh', $yh);
                $this->assign('gather', $gather);
                $this->meta_title = '平台商户详情';
                $this->display();
            } else {
                echo "<script>alert('修改失败!');</script>";
                die;
            }


        } else {
            $uid = I('get.uid');
            $yh = D('Ptyh')->where("uid=" . $uid)->find();
            $gather = D('Gather')->where("uid=" . $yh['uid'])->find();


            $a = D('Dingdan')->where(['uid' => $one['uid']])->select();
            $b = D('Dividend')->where(['uid' => $one['uid']])->select();
            $c = D('Extract')->where(['uid' => $one['uid']])->select();
            $d = D('Split')->where(['uid' => $one['uid']])->select();

            $e = D('Youka')->where(['uid' => $one['uid']])->select();
            $f = D('Xyk')->where(['uid' => $one['uid']])->select();
            $g = D('Wxpay')->where(['uid' => $one['uid']])->select();


            $lists = array();
            $key = 0;
            foreach ($a as $v) {//收益
                $lists[$key]['uid'] = $v['uid'];
                $lists[$key]['danhao'] = $v['danhao'];
                $lists[$key]['trade_no'] = $v['trade_no'];
                $lists[$key]['total'] = $v['pay_money'];
                $lists[$key]['money'] = $v['yh_money'];//当时的收益，费率可能会变
                $lists[$key]['t_money'] = $v['t_money'];


                $lists[$key]['type'] = 1;
                $lists[$key]['time'] = $v['pay_time'];
                $lists[$key]['status'] = $v['status'];
                $key++;

            }
            foreach ($b as $v) {//分润
                $lists[$key]['uid'] = $v['uid'];
                $lists[$key]['danhao'] = $v['danhao'];
                $lists[$key]['trade_no'] = $v['trade_no'];
                $lists[$key]['total'] = $v['total'];
                $lists[$key]['money'] = $v['divide'];
                $lists[$key]['type'] = 2;
                $lists[$key]['time'] = $v['time'];
                $lists[$key]['status'] = $v['status'];
                $lists[$key]['t_money'] = $v['t_money'];
                $key++;

            }


            foreach ($c as $v) {//提现
                $lists[$key]['uid'] = $v['uid'];
                $lists[$key]['danhao'] = $v['out_biz_no'];
                $lists[$key]['trade_no'] = $v['order_id'];
                $lists[$key]['total'] = $v['money'];
                $lists[$key]['money'] = $v['money'];//到账金额
                $lists[$key]['type'] = 3;
                $lists[$key]['time'] = $v['time'];
                $lists[$key]['status'] = $v['status'];
                $lists[$key]['t_money'] = $v['t_money'];
                $key++;

            }

            foreach ($d as $v) {//口碑收益
                // $one=D('Dingdan')->where(['trade_no'=>$v['trade_no']])->find();
                $lists[$key]['uid'] = $v['uid'];
                $lists[$key]['danhao'] = $v['out_request_no'];
                $lists[$key]['trade_no'] = $v['trade_no'];
                $lists[$key]['total'] = $v['money_in'];
                $lists[$key]['money'] = $v['sh_money'];
                $lists[$key]['t_money'] = $v['t_money'];
                $lists[$key]['type'] = 4;
                $lists[$key]['time'] = $v['time'];
                $lists[$key]['status'] = $v['status'];
                $key++;

            }
// print_r($e);
            foreach ($e as $v) {//油卡
                // print_r($v);
                $lists[$key]['uid'] = $v['uid'];
                $lists[$key]['danhao'] = $v['orderId'];
                $lists[$key]['total'] = $v['face'];
                $lists[$key]['money'] = $v['yh_money'];//当时的收益，费率可能会变
                $lists[$key]['t_money'] = $v['t_money'];


                $lists[$key]['type'] = 5;
                $lists[$key]['time'] = $v['time'];
                $lists[$key]['status'] = $v['re_status'];
                $key++;

            }

            foreach ($f as $v) {//收益
                $lists[$key]['uid'] = $v['uid'];
                $lists[$key]['danhao'] = $v['danhao'];
                $lists[$key]['trade_no'] = $v['trade_no'];
                $lists[$key]['total'] = $v['pay_money'];
                $lists[$key]['money'] = $v['yh_money'];//当时的收益，费率可能会变
                $lists[$key]['t_money'] = $v['t_money'];


                $lists[$key]['type'] = 1;
                $lists[$key]['time'] = $v['pay_time'];
                $lists[$key]['status'] = $v['status'];
                $key++;

            }

            foreach ($g as $v) {//微信收款 收益
                $lists[$key]['uid'] = $v['uid'];
                $lists[$key]['danhao'] = $v['danhao'];
                $lists[$key]['trade_no'] = $v['trade_no'];
                $lists[$key]['total'] = $v['pay_money'];
                $lists[$key]['money'] = $v['yh_money'];//当时的收益，费率可能会变
                $lists[$key]['t_money'] = $v['t_money'];


                $lists[$key]['type'] = 1;
                $lists[$key]['time'] = $v['pay_time'];
                $lists[$key]['status'] = $v['status'];
                $key++;

            }

            foreach ($lists as $v) {
                $one = D('Linshi')->where(['danhao' => $v['danhao']])->find();
                if (empty($one)) {
                    D('Linshi')->add($v);
                }

            }


            $this->assign('yh', $yh);
            $this->assign('gather', $gather);
            $this->meta_title = '平台商户详情';
            $this->display();
        }

    }


    // 平台商户详情
    public function yh_view2()
    {

        if (IS_POST) {
            $uid = $_POST['uid'];
            $status = I('status');
            if ($status == -1) {
                D('Ptyh')->where('uid=' . $uid)->delete();
                $this->redirect('ptyh2');
            } else {
                $data1 = [
                    'name' => $_POST['name'],
                    'alipay' => $_POST['alipay'],
                    'status' => 1,

                ];
                $data2 = [
                    'path1' => $_POST['path1'],
                    'path2' => $_POST['path2'],
                    'status' => $_POST['status'],
                ];
                $id1 = D('Ptyh')->where('uid=' . $uid)->save($data1);
                $id2 = D('Gather')->where('uid=' . $uid)->save($data2);


                if ($id2 > 0 || $id1 > 0) {
                    $this->redirect('ptyh2');
                } else {
                    echo "<script>alert('修改失败!');history.go(-1)</script>";
                    die;
                }
            }
        } else {
            $id = I('get.id');
            $yh = D('Ptyh')->where("id=" . $id)->find();

            $gather = D('Gather')->where("uid=" . $yh['uid'])->find();
            $this->assign('yh', $yh);
            $this->assign('gather', $gather);
            $this->meta_title = '平台商户详情';
            $this->display();
        }

    }


    function yh_delete()
    {

        // print_r($_POST);
        $uids = I('post.uids');
        if (empty($uids)) {
            // 什么都不干
            echo 0;
            die;
        } else {
            foreach ($uids as $key => $v) {
                D('Ptyh')->where(['uid' => $v])->delete();
                D('Gather')->where(['uid' => $v])->delete();
            }

            echo 1;
            die;

        }
    }


// 平台用户列表
    public function ptyh()
    {


        if (IS_POST) {
            $uid = I('post.uid');
            $type = I('post.type');
            $status = I('post.status');

            $ids = I('post.ids');
            if ($type == 1) {
                // 信用卡
                if (empty($ids)) {
                    print_r('请选择需要修改的用户！');
                    die;
                }
                if (empty($type)) {
                    print_r('请选择修改通道！');
                    die;
                }
                $data = array(
                    'status_xy' => $status,
                );
                foreach ($ids as $v) {
                    $id = D('Gather')->where(['uid' => $v])->save($data);
                    if ($id > 0) {
                        echo "修改成功！";
                        die;
                    } else {
                        echo "修改失败！";
                        die;
                    }
                }
            } else if ($type == 2) {
                // 花呗
                if (empty($ids)) {
                    print_r('请选择需要修改的用户！');
                    die;
                }
                if (empty($type)) {
                    print_r('请选择修改通道！');
                    die;
                }
                $data = array(
                    'status_hb' => $status,
                );
                foreach ($ids as $v) {
                    $id = D('Gather')->where(['uid' => $v])->save($data);
                    if ($id > 0) {
                        echo "修改成功！";
                        die;
                    } else {
                        echo "修改失败！";
                        die;
                    }
                }
            } else if ($type == 3) {
                // 花呗分期
                if (empty($ids)) {
                    print_r('请选择需要修改的用户！');
                    die;
                }
                if (empty($type)) {
                    print_r('请选择修改通道！');
                    die;
                }
                $data = array(
                    'status_fq' => $status,
                );
                foreach ($ids as $v) {
                    $id = D('Gather')->where(['uid' => $v])->save($data);
                    if ($id > 0) {
                        echo "修改成功！";
                        die;
                    } else {
                        echo "修改失败！";
                        die;
                    }
                }
            } else if ($type == 4) {
                // 条码
                if (empty($ids)) {
                    print_r('请选择需要修改的用户！');
                    die;
                }
                if (empty($type)) {
                    print_r('请选择修改通道！');
                    die;
                }
                $data = array(
                    'status_tm' => $status,
                );
                foreach ($ids as $v) {
                    $id = D('Gather')->where(['uid' => $v])->save($data);
                    if ($id > 0) {
                        echo "修改成功！";
                        die;
                    } else {
                        echo "修改失败！";
                        die;
                    }
                }
            } else if ($type == 'status') {
                $status = I('post.status');

                $id = D('Gather')->where("uid={$uid}")->save(['status' => $status]);
                if ($id > 0) {
                    echo 1;
                    die;
                } else {
                    echo 0;
                    die;
                }
            } elseif ($type == 'setkbxx') {
                //设置码商
                //ajax 设置码商

                $uid = I('post.uid');

                $ptyh = M('ptyh')->find($uid);

                $model = D('Kbxx');
                $par['uid'] = $uid;
                $par['name'] = $ptyh['name'];
                $par['phone'] = $ptyh['phone'];
                $par['real_status'] = 1;
                $data2 = [
                    'uid' => $uid,
                    'money' => 0,
                    'count' => 0,
                    'status' => 1,
                ];

                $gather = M('Gather');
                $_one = $gather->where('uid=' . $uid)->find();
                if (empty($_one)) {
                    $id2 = $gather->add($data2);
                }
                $one = $model->where('uid=' . $this->uid)->find();
                if (!empty($one)) {
                    $this->showError('已存在商户信息');
                }

                $id = $model->add($par);

                if ($id) {
                    $this->showSuccess('设置成功');
                } else {
                    $this->showError('设置失败');
                }

            }elseif ($type == 'unsetkbxx') {
                //取消码商
                //ajax 取消码商

                $uid = I('post.uid');

                $ptyh = M('ptyh')->find($uid);

                $model = D('Kbxx');
                $one = $model->where('uid=' . $uid)->find();
                if (empty($one)) {
                    $this->showError('商户信息不存在');
                }

                $delresult = $model->where('id=' . $one['id'])->delete();

                if ($delresult) {
                    $this->showSuccess('取消码商成功');
                } else {
                    $this->showError('取消码商失败');
                }

            } else {

                $frozen = I('post.frozen');
                $frozen_val = I('post.frozen_val');
                if ($frozen == 1) {
                    $id = D('Gather')->where("uid={$uid}")->save(['frozen' => $frozen, 'frozen_cause' => '']);
                    if ($id > 0) {
                        echo 1;
                        die;
                    } else {
                        echo 0;
                        die;
                    }
                } else {
                    $id = D('Gather')->where("uid={$uid}")->save(['frozen' => $frozen, 'frozen_cause' => $frozen_val]);
                    if ($id > 0) {
                        $list = D('Ptyh')->select();
                        $result = $this->subtree($list, $uid);
                        foreach ($result as $key => $v) {
                            D('Gather')->where("uid=$v")->save(['frozen' => $frozen, 'frozen_cause' => '您的上级操作冻结，如有疑问请在商户控制台->我的团队找到您的上级进行核实。']);
                        }
                        echo 1;
                        die;
                    } else {
                        echo 0;
                        die;
                    }
                }


            }


        } else {

            $list = $this->lists('Ptyh', ['status' => 1]);
            foreach($list as $k => $v){
                $list[$k]['gather'] = M('gather')->where(['uid' => $v['uid']])->find();
            }
            $usercount = M('ptyh')->where(['status' => 1])->count();
            $sum['total'] = D('Gather')->sum('money');
            $time1 = strtotime(date("Ymd", strtotime("+1 day")));
            $time2 = strtotime(date("Ymd"));
            $sum['td_in'] = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

            $sum['td_out'] = D('Extract')->where("status=1 and time between $time2 and $time1")->sum('money');
            $sum['divide'] = D('gather')->sum('fenrun');
            $sum['t_money'] = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');
            $sum['yongjin'] = D('gather')->sum('yongjin');
            $this->assign('usercount',$usercount);
            $this->assign('sum', $sum);
            $this->assign('_list', $list);
            $this->meta_title = '平台用户';
            $this->display();


        }

    }


    // 平台用户列表
    public function ptyh2()
    {


        if (IS_POST) {
            // 一键审核所选人员
            if (!empty(I('post.ids'))) {
                $ids = I('post.ids');
                foreach ($ids as $key => $v) {
                    $id = D('Ptyh')->where(['uid' => $v])->save(['status' => 1]);

                }
                print_r('审核完毕');
                die;
            }

        }

        $map['status'] = 0;
        $map['identify'] = array('neq', '');
        $list = $this->lists('Ptyh', $map);
        $sum['total'] = D('Gather')->sum('money');
        $time1 = strtotime(date("Ymd", strtotime("+1 day")));
        $time2 = strtotime(date("Ymd"));
        $sum['td_in'] = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

        $sum['td_out'] = D('Extract')->where("status=1 and time between $time2 and $time1")->sum('money');
        $sum['divide'] = D('Dividend')->where("status=1")->sum('divide');
        $sum['t_money'] = D('Dingdan')->where("status=1")->sum('pay_money');
        $this->assign('sum', $sum);
        $this->assign('_list', $list);
        $this->meta_title = '平台用户';
        $this->display();


    }


    // 递归查找下级下级下级------------------------------------------
    function subtree($arr, $uid)
    { //id表示我们最初查找的id
        static $subs = array();
        foreach ($arr as $v) {

            if ($v['pid'] == $uid) {
                $subs[] = $v['uid'];
                $this->subtree($arr, $v['uid']); //最重要的一步
            }
        }
        return $subs;
    }


    // 平台用户查询
    public function find_one()
    {
        $title = I('get.title');
        $tatus = I('get.status');
        $type = I('get.type');


        $num = intval($title);
        if ($num != 0 && strlen($title) == 14) {   //纯数字 查询编号
            $list = $this->lists('Ptyh', ['yh_uid' => $title]);
        } else {
            // 不是数字  名字或者店名
            $map = [
                'name' => array('like', "%{$title}%"),

            ];
            $list = $this->lists('Ptyh', $map);

            if (empty($list)) {
                $map = [
                    'shop_name' => array('like', "%{$title}%"),

                ];
                $list = $this->lists('Ptyh', $map);
            }
        }

        $this->assign('_list', $list);
        $this->meta_title = '平台用户';
        $this->display('Alipay/ptyh');
    }


// 平台用户订单列表
    public function dingdan()
    {

        $type = I('get.type');
        $map = array();
        $order = 'pay_time desc';
        if ($type == 'today') {
            $time1 = strtotime(date("Ymd"));
            $time2 = strtotime(date("Ymd", time() + 86400));
            $map['pay_time'] = array(array('gt', $time1), array('lt', $time2), 'and');
            $map['status'] = 1;
        } elseif ($type == 'success') {

            $map['status'] = array('eq', 1);

        } elseif ($type == 'fail') {

            $map['status'] = array('eq', 0);

        }


        $list = $this->lists('Dingdan', $map, $order);


        // $list   =   $this->lists('Dingdan','','pay_time desc','');
        $sum['total'] = D('Gather')->sum('money');
        $time1 = strtotime(date("Ymd", strtotime("+1 day")));
        $time2 = strtotime(date("Ymd"));
        $sum['td_in'] = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

        $sum['td_out'] = D('Extract')->where("status=1 and time between $time2 and $time1")->sum('money');
        $sum['divide'] = D('Dividend')->where("status=1")->sum('divide');
        $sum['t_money'] = D('Dingdan')->where("status=1")->sum('pay_money');

        foreach($list as $k => $v){
            $list[$k]['shop_name'] = M('kbsh')->where(['user_id' => $v['seller_id']])->getField('name');
        }
        $this->assign('sum', $sum);
        $this->assign('_list', $list);
        $this->meta_title = '订单记录';
        $this->display();
    }


    // 平台用户订单详情
    public function dingdan_view()
    {

        // 不同的表根据id不可找到唯一订单-----------------需要修改
        $id = I('get.id');
        $type = I('get.type');
        if ($type == 1) {
            $dingdan = D('Xyk')->where(['id' => $id])->find();
        } else if ($type == 2) {
            $dingdan = D('Wxpay')->where(['id' => $id])->find();
        } else {
            $dingdan = D('Dingdan')->where(['id' => $id])->find();
        }


        $dingdan['shop_name'] = M('kbsh')->where(['user_id' => $dingdan['seller_id']])->getField('name');
        $this->assign('info', $dingdan);
        $this->meta_title = '订单详情';
        $this->display();
    }

    // 单笔回款
    public function trans()
    {
        $id = I('post.id');
        $money = I('post.money');
        $out_biz_no = I('post.no');
        if (!empty($id) && !empty($money) && !empty($out_biz_no)) {

            $trans = D('Trans')->where(['out_biz_no' => $out_biz_no])->find();
            $ptyh = D('Ptyh')->where(['uid' => $trans['uid']])->find();
            Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
            $transfer = new \Alipay;
            $alipay = $id;


            $out_biz_no = $out_biz_no;
            $payer_show_name = $ptyh['name'];
            $remark = "转账";


            // if(preg_match('/^[hft]/', $out_biz_no)){
            $amount = $money - 1;
            $adata = D('Adata')->where(['id' => 1])->find();
            file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'transfer5转账参数: '. json_encode([$out_biz_no, $alipay, $amount, $remark, $payer_show_name, $adata]) . PHP_EOL, FILE_APPEND);
            $result = $transfer->transfer5($out_biz_no, $alipay, $amount, $remark, $payer_show_name, $adata);

            // }else if(preg_match('/^[x]/', $out_biz_no)){
            //     $amount         = $money;
            //     $result=$transfer->transfer1($out_biz_no,$alipay,$amount,$remark,$payer_show_name);
            // }


            // $time1=strtotime(date("Ymd",strtotime("+1 day")));
            // $time2=strtotime(date("Ymd"));
            // $td_money=D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

            if (empty($result->sub_msg) && $result->out_biz_no == $out_biz_no) {
                // 说明是成功的   1、提现状态修改 2、提现次数、用户余额修改
                $trade_num = $result->order_id;
                D('Trans')->where(['out_biz_no' => $out_biz_no])->save(['status' => 1, 'trade_num' => $trade_num, 'time' => $result->pay_date]);
                echo "转账成功！本次转出{$amount}元";
                die;

            } else {
                if (preg_match('/^[x]/', $out_biz_no)) {
                    D('Tongdao')->where(['id' => 1])->save(['hk_xy' => 0]);
                }
                echo $result->sub_msg;
                die;
            }
        }
    }

    // 平台用户订单查询
    public function find_dingdan()
    {
        $title = I('get.title');
        $tatus = I('get.status');
        $id = I('get.id');

        $list = array();
        if ($id == 1) {
            // 订单
            if (strlen($title) == 14) {
                $yh = D('Ptyh')->where(['yh_uid' => $title])->find();
                $list = $this->lists('Dingdan', ['uid' => $yh['uid']]);
            } else if (strlen($title) == 20) {
                $list = $this->lists('Dingdan', ['danhao' => $title]);
            } else if (strlen($title) == 28) {
                $list = $this->lists('Dingdan', ['trade_no' => $title]);
            }


            if (empty($list)) {
                // 不是数字  名字或者店名

                $yh = D('Ptyh')->where(['name' => array('like', "%{$title}%")])->find();
                if (!empty($yh)) {
                    $list = $this->lists('Dingdan', ['uid' => $yh['uid']]);
                }

            }


            if (empty($list)) {
                $yh = D('Ptyh')->where(['shop_name' => array('like', "%{$title}%")])->find();
                if (!empty($yh)) {
                    $list = $this->lists('Dingdan', ['uid' => $yh['uid']]);
                }
            }
        } else if ($id == 2) {
            // 信用卡
            if (strlen($title) == 14) {
                $yh = D('Ptyh')->where(['yh_uid' => $title])->find();
                $list = $this->lists('Xyk', ['uid' => $yh['uid']]);
            } else if (strlen($title) == 20) {
                $list = $this->lists('Xyk', ['danhao' => $title]);
            } else if (strlen($title) == 28) {
                $list = $this->lists('Xyk', ['trade_no' => $title]);
            }


            if (empty($list)) {
                // 不是数字  名字或者店名

                $yh = D('Ptyh')->where(['name' => array('like', "%{$title}%")])->find();
                if (!empty($yh)) {
                    $list = $this->lists('Xyk', ['uid' => $yh['uid']]);
                }

            }


            if (empty($list)) {
                $yh = D('Ptyh')->where(['shop_name' => array('like', "%{$title}%")])->find();
                if (!empty($yh)) {
                    $list = $this->lists('Xyk', ['uid' => $yh['uid']]);
                }
            }
        } else if ($id = 3) {
            // 微信
            if (strlen($title) == 14) {
                $yh = D('Ptyh')->where(['yh_uid' => $title])->find();
                $list = $this->lists('Wxpay', ['uid' => $yh['uid']]);
            } else if (strlen($title) == 20) {
                $list = $this->lists('Wxpay', ['danhao' => $title]);
            } else if (strlen($title) == 28) {
                $list = $this->lists('Wxpay', ['trade_no' => $title]);
            }


            if (empty($list)) {
                // 不是数字  名字或者店名

                $yh = D('Ptyh')->where(['name' => array('like', "%{$title}%")])->find();
                if (!empty($yh)) {
                    $list = $this->lists('Wxpay', ['uid' => $yh['uid']]);
                }

            }


            if (empty($list)) {
                $yh = D('Ptyh')->where(['shop_name' => array('like', "%{$title}%")])->find();
                if (!empty($yh)) {
                    $list = $this->lists('Wxpay', ['uid' => $yh['uid']]);
                }
            }
        }

        $this->assign('_list', $list);
        $this->meta_title = '订单记录';
        if ($id == 1) {
            $this->display('Alipay/dingdan');
        } else if ($id == 2) {
            $this->display('Alipay/xyk_dingdan');
        } else if ($id == 3) {
            $this->display('Alipay/wx_dingdan');
        }

    }
    // 20171209342660   20171213143001160192    2017121321001004670504094730

    // 提现记录列表
    public function tixian()
    {

        $type = I('get.type');
        $map = array();
        $order = 'time desc';
        if ($type == 'today') {
            $time1 = strtotime(date("Ymd"));
            $time2 = strtotime(date("Ymd", time() + 86400));
            $map['time'] = array(array('gt', $time1), array('lt', $time2), 'and');
            $map['status'] = 1;
        } elseif ($type == 'success') {

            $map['status'] = array('eq', 1);

        } elseif ($type == 'fail') {

            $map['status'] = array('eq', 0);

        }


        $list = $this->lists('Extract', $map, $order);

        // $list   =   $this->lists('Extract','','time desc','');
        $sum['total'] = D('Gather')->sum('money');
        $time1 = strtotime(date("Ymd", strtotime("+1 day")));
        $time2 = strtotime(date("Ymd"));
        $sum['td_in'] = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

        $sum['td_out'] = D('Extract')->where("status=1 and time between $time2 and $time1")->sum('money');
        $sum['divide'] = D('Dividend')->where("status=1")->sum('divide');
        $sum['t_money'] = D('Dingdan')->where("status=1")->sum('pay_money');
        $sum['yongjin'] = D('split')->where('status=1')->sum('sh_money');
        $this->assign('sum', $sum);
        $this->assign('_list', $list);
        $this->meta_title = '提现记录';
        $this->display();
    }

    // 平台用户订单查询
    public function find_tixian()
    {
        $title = I('get.title');
        $tatus = I('get.status');
        $type = I('get.type');

        if (strlen($title) == 14) {  //编号
            $yh = D('Ptyh')->where(['yh_uid' => $title])->find();
            $list = $this->lists('Extract', ['uid' => $yh['uid']]);

        } else if (strlen($title) == 20) {
            $list = $this->lists('Extract', ['out_biz_no' => $num]);
        } else if (strlen($title) == 28) {
            $list = $this->lists('Extract', ['order_id' => $num]);
        }

        if (empty($list)) {
            // 不是数字  名字或者店名            

            $yh = D('Ptyh')->where(['name' => array('like', "%{$title}%")])->find();
            if (!empty($yh)) {
                $list = $this->lists('Extract', ['uid' => $yh['uid']]);
            }

        }


        if (empty($list)) {

            $yh = D('Ptyh')->where(['shop_name' => array('like', "%{$title}%")])->find();

            if (!empty($yh)) {
                $list = $this->lists('Extract', ['uid' => $yh['uid']]);
            }

        }

        $this->assign('_list', $list);
        $this->meta_title = '提现记录';
        $this->display('Alipay/tixian');
    }


    //分账列表
    public function split()
    {
        $type = I('get.type');
        $where = array();
        if ($type == 1) {
            $where = array('_string' => "`sub_msg` is not null and `sub_msg` !=''");
            $list = $this->lists('Split', $where, 'time desc', '');
        } else {
            $list = $this->lists('Split', $where, 'time desc', '');
        }

        $this->assign('_list', $list);
        $this->meta_title = '分账记录';
        $this->display();
    }

// 投诉
    public function tousu()
    {

        $list = $this->lists('Tousu');
        $this->assign('_list', $list);
        $this->meta_title = '投诉列表';
        $this->display();

    }

    public function ts_view()
    {

        if (IS_POST) {

            $id = I('post.id');
            $status = I('post.status');
            if (!empty($id)) {

                $ids = D('Tousu')->where('id=' . $id)->save(['status' => $status]);
                if ($ids > 0) {
                    echo 1;
                    die;
                } else {

                    echo 0;
                    die;
                }
            } else {
                echo '参数不正确';
                die;
            }
        } else {
            $id = $_GET['id'];

            $one = D('Tousu')->where("id={$id}")->find();

            if ($one['status'] == 0) {
                D('Tousu')->where('id=' . $id)->save(['status' => 2]);
            }
            $this->assign('_list', $one);


            $this->meta_title = '投诉详情';
            $this->display();
        }


    }

// 申诉
    public function shensu()
    {

        $list = $this->lists('Shensu');

        $this->assign('_list', $list);
        $this->meta_title = '申诉列表';
        $this->display();

    }

    public function ss_view()
    {

        if (IS_POST) {

            $id = I('post.id');
            $uid = I('post.uid');
            $status = I('post.status');
            if (!empty($id)) {

                $ids = D('Shensu')->where('id=' . $id)->save(['status' => $status]);
                D('Gather')->where("uid={$uid}")->save(['frozen' => 1]);

                if ($ids > 0) {
                    echo 1;
                    die;
                } else {

                    echo 0;
                    die;
                }
            } else {
                echo '参数不正确';
                die;
            }
        } else {
            $id = $_GET['id'];

            $one = D('Shensu')->where("id={$id}")->find();

            if ($one['status'] == 0) {
                D('Shensu')->where('id=' . $id)->save(['status' => 2]);
            }
            $this->assign('_list', $one);

            $this->meta_title = '申诉详情';
            $this->display();
        }


    }


    /**
     * 系统公告
     */

    public function gg()
    {


        if (IS_POST) {

            $type = I('post.type', '正常运行'); //系统运行状态
            $remark = I('post.remark'); //自定义语句
            $members = D('Ptyh')->select();

            $data = [
                'title' => '您好，系统做出以下调整，请悉知',
                'name' => '绿叶收银台',
                'status' => $type,
                'time' => date("Y-m-d H:i:s"),
                'remark' => $remark,
            ];

            $res = M('gg')->add($data);
            foreach ($members as $key => $v) {
                if (empty($v['name'])) {

                } else {

                    $one = D('Gg')->where(['uid' => $v['uid']])->find(); //公告
                    if ($one['status'] == 0) {

                        $member = D('Ptyh')->where(['uid' => $one['uid']])->find();
                        if (!empty($member)) {
                            D('Notice')->weixin(2, $member['wx_uid'], $data);


                        } else {
                            // echo '未绑定微信';die;
                        }

                    }

                }

            }

//            $this->redirect('gg');

            if ($res) {
                echo json_encode(['code' => 1, 'msg' => '发布成功', 'data' => '']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '发布失败', 'data' => '']);
            }

        } else {
            $this->meta_title = '公告';
            $this->display();
        }

    }

    public function ajaxAddGg()
    {
        $type = I('post.type', '正常运行'); //系统运行状态
        $remark = I('post.remark'); //自定义语句
        $title = I('post.title', '您好，系统做出以下调整，请悉知');
        $members = D('Ptyh')->select();

        $data = [
            'title' => $title,
            'name' => '绿叶收银台',
            'status' => $type,
            'time' => date("Y-m-d H:i:s"),
            'remark' => $remark,
        ];

        $res = M('gg')->add($data);

        /*
        foreach ($members as $key => $v) {
            if(empty($v['name'])){

            }else{

                $one=D('Gg')->where(['uid'=>$v['uid']])->find(); //公告
                if($one['status']==0){

                    $member=D('Ptyh')->where(['uid'=>$one['uid']])->find();
                    if(!empty($member)){
                        D('Notice')->weixin(2,$member['wx_uid'],$data);


                    }else{
                        // echo '未绑定微信';die;
                    }

                }

            }

        }
        */

//            $this->redirect('gg');

        if ($res) {
            echo json_encode(['code' => 1, 'msg' => '发布成功', 'data' => '']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '发布失败', 'data' => '']);
        }
    }


    // 分润
    public function divide()
    {

        $list = $this->lists('Dividend');

        $this->assign('_list', $list);
        $this->meta_title = '分润列表';
        $this->display();

    }


    // 提现
    public function tixian_by()
    {
// print_r($_POST);die;
        $uid = I('post.uid');
        $one = D('Gather')->where(['uid' => $uid])->find();
        if ($one['frozen'] == 0) {
            echo "此账户已冻结，不可以提现！";
            die;
        }
        $yh = D('Ptyh')->where(['uid' => $uid])->find();
        $alipay = $yh['alipay'];
//        $amount = $one['money'];
        $amount = ($one['yongjin']*100 + $one['fenrun']*100)/100;
        $out_biz_no = date("YmdHis") . rand(100000, 999999);
        $one = D('Ptyh')->where('uid=' . $uid)->find();
        $payee_real_name = $one['name'];
        $payer_show_name = '绿叶收银台';
        $time = time();

        // 判断结束
        $extract = array(
            'uid' => $uid,
            'money' => $amount,//存入的是不扣除手续费的金额
            'time' => time(),
            'status' => 0,
            'out_biz_no' => $out_biz_no,
        );

        // print_r($extract);die;
        $id = D('Extract')->add($extract);

        // 调用预下单接口得到付款二维码
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $transfer = new \Alipay;

        $adata = D('Adata')->where(['id' => 1])->find();
        // $transfer->app_auth_token=$app_auth_token;//口碑商家授权令牌（代收款）!!!!!!!!!!!!!!!!该参数是公共参数！！！！！！！！！！！！
        $remark = '商户提现';
        $_amount = $amount;//实际到款


        // 查看当日提现总金额  超过95万则使用另一个支付宝
        $time1 = strtotime(date("Ymd", strtotime("+1 day")));
        $time2 = strtotime(date("Ymd"));
        $td_money = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

        $result = $transfer->transfer8($out_biz_no, $alipay, $_amount, $remark, $payee_real_name, $payer_show_name, $adata);


        if (empty($result->sub_msg) && $result->out_biz_no == $out_biz_no) {
            // 说明是成功的   1、提现状态修改 2、提现次数、用户余额修改
            $out_no = $result->out_biz_no;
            $order_id = $result->order_id;
            $extract = D('Extract')->where('out_biz_no=' . $out_no)->find();

            D('Extract')->where('out_biz_no=' . $out_no)->save(['status' => 1, 'order_id' => $order_id]);

            $one = D('Gather')->where('uid=' . $extract['uid'])->find();
//            $money = $one['money'] - $amount;

            $count = $one['count'] + 1;
//            D('Gather')->where('uid=' . $extract['uid'])->save(['money' => $money, 'count' => $count]);
            D('Gather')->where('uid=' . $extract['uid'])->save(['yongjin' => 0,'fenrun' => 0, 'count' => $count]);


            $data = [
                'name' => $payee_real_name,
                'money' => $amount,
                'remark' => '提现单号：' . $out_biz_no . '，如有疑问请联系客服进行咨询。',
            ];

            $member = D('Ptyh')->where(['uid' => $uid])->find();


            echo "提现成功";
            die;

        } else {
            echo $result->sub_msg;
            die;

        }

    }


// 通道开启或关闭
    public function close()
    {
        if (IS_POST) {
            // print_r($_POST);die;
            $id = D('Tongdao')->where(['id' => 1])->save(I('post.'));
            echo $id;
        } else {
            $info = D('Tongdao')->find();
            $this->assign('info', $info);
            $this->meta_title = '通道管理';
            $this->display();
        }
    }

    // 更换支付宝
    public function change_alipay()
    {
        if (IS_POST) {
            print_r($_POST);
            die;
        } else {
            $info = D('Tongdao')->find();
            $this->assign('info', $info);
            $this->meta_title = '通道管理';
            $this->display();
        }
    }


    public function youka()
    {

        $type = I('get.type');
        $map = array();
        $order = 'time desc';
        if ($type == 'today') {
            $time1 = strtotime(date("Ymd"));
            $time2 = strtotime(date("Ymd", time() + 86400));
            $map['time'] = array(array('gt', $time1), array('lt', $time2), 'and');
            // $map['re_status']       =1;
        } elseif ($type == 'success') {

            $map['re_status'] = 1;

        } elseif ($type == 'fail') {

            $map['re_status'] = 2;

        }


        $list = $this->lists('Youka', $map, $order);

        $this->assign('_list', $list);
        $this->meta_title = '油卡订单';
        $this->display();
    }


    // 更换支付宝
    public function change_ali()
    {
        if (IS_POST) {
            $id = D('Adata')->where(['id' => 1])->save(I('post.'));
            echo $id;
            die;

        } else {
            $info = D('Adata')->find();
            $this->assign('info', $info);
            $this->meta_title = '更改收款支付宝';
            $this->display();
        }
    }


    public function ptdata()
    {
        if (IS_POST) {
            $ptdata = D('Ptdata')->where(['id' => 1])->find();
            $dvalue = I('post.pt_rate') - $ptdata['pt_rate'];
            $dvalue2 = I('post.pt_rate2') - $ptdata['pt_rate2'];
            if ($dvalue != 0) {
                // 值改变   1 将所有的花呗费率改成现在的平台费率  2 用户的upset都加/减差值
                D('Gather')->where(1)->save(['path1' => I('post.pt_rate')]);
                D('Gather')->where(1)->setInc('up_set', $dvalue);

            }
            if ($dvalue2 != 0) {
                // 值改变   1 将所有的花呗费率改成现在的平台费率  2 用户的upset都加/减差值
                D('Gather')->where(1)->save(['path2' => I('post.pt_rate2')]);
                D('Gather')->where(1)->setInc('up_set2', $dvalue2);

            }
            $id = D('Ptdata')->where(['id' => 1])->save(I('post.'));
            echo $id;
            die;

        } else {
            $info = D('Ptdata')->find();
            $this->assign('info', $info);
            $this->meta_title = '平台基础信息';
            $this->display();
        }
    }


    // 更换支付宝
    public function change_al()
    {
        if (IS_POST) {


            $id = D('Adata')->where(['id' => 1])->save(I('post.'));
            echo $id;
            die;
        } else {
            $info = D('Adata')->find();
            $this->assign('info', $info);
            $this->meta_title = '更改收款支付宝';
            $this->display();
        }
    }

    public function addalipay(){
        $data = $_POST['data'];
        $data[0]['value'] = intval($data[0]['value']);

        $handle = array();
        for ($i = 0; $i < count($data); $i++) {
            $handle[$data[$i]['name']] = $data[$i]['value'];
        }

        $id = D('Alipays')->add($handle);

        $alipays = M('alipays')->find($id);

//        $redis = new \Predis\Client(C('REDIS'), ['prefix' => C('REDIS_PREFIX')]);
//        $rediskey = \Home\Logic\PayLogic::getRedisKeyByType($alipays['type']);
//        $redis->lpush($rediskey,$id);

        echo $id;
        die;
    }

    /**
     * 添加手机网站支付
     */
    public function alipay_list()
    {

        if (IS_POST) {
            $type = I('post.type');
            if ($type == 1) {

            } else if ($type == 2) {
                $one = D('Alipays')->where(['id' => I('post.id')])->find();
                if (!empty($one)) {
                    ob_clean();
                    echo json_encode($one);
                    die;

                } else {
                    ob_clean();
                    echo json_encode(['info' => 0]);
                    die;
                }


            } else if ($type == 3) {
                //手机网站支付
                $id = I('post.id');
                $data = $_POST['data'];
                $handle = array();
                for ($i = 0; $i < count($data); $i++) {
                    $handle[$data[$i]['name']] = $data[$i]['value'];
                }
                $id = D('Alipays')->where(['id' => $id])->save($handle);
                echo $id;
                die;

            } else if ($type == 4) {

                //删除
                $rowid = I('post.id');
                $alipays = M('alipays')->find($rowid);
                $id = D('Alipays')->where(['id' => I('post.id')])->delete();
                $redis = new \Predis\Client(C('REDIS'),['prefix' => C('REDIS_PREFIX')]);
                $rediskey = \Home\Logic\PayLogic::getRedisKeyByType($alipays['type']);
                $redis->lrem($rediskey,1,$rowid);
                echo $id;
                die;
            } else if ($type == 5) {
                if (I('post.status') == 0) {
                    $id = D('Alipays')->where(['id' => I('post.id')])->save(['status' => 1, 'cause' => '']);
                    echo $id;
                    die;
                } else {
                    $id = D('Alipays')->where(['id' => I('post.id')])->save(['status' => 0, 'cause' => '手动下架']);
                    echo $id;
                    die;
                }


            }


        } else {

            // $where=array();
            // $title=I('get.title');
            // if(strlen($title)==16){
            //     $where['user_id']=$title;
            // }else{
            //     $where['name']=array('like',"%{$title}%");
            // }
            // $list   =   $this->lists('Kbsh',$where);   
            // if(empty($list)){
            //     $one   =D('Kbxx')->where(['name'=>array('like',"%{$title}%")])->find();  
            //     $list   =   $this->lists('Kbsh',['uid'=>$one['uid']]); 
            // }

//            $list = $this->lists('Alipays');
            $list = M('alipays')->order('id','desc')->select();


            $this->assign('_list', $list);
            $this->meta_title = '收款支付宝';
            $this->display();

        }

    }

    public function saveMobilePay(){
        $data = $_POST['data'];
        $handle = array();
        for ($i = 0; $i < count($data); $i++) {
            $handle[$data[$i]['name']] = $data[$i]['value'];
        }
        $handle['type'] = 1;
        $id = D('Alipays')->add($handle);
        echo $id;
        die;
    }


    /**
     * 上架下架
     */
    public function tx_alipay_list()
    {

        if (IS_POST) {
            $type = I('post.type');
            if ($type == 1) {
                $data = $_POST['data'];
                $handle = array();
                for ($i = 0; $i < count($data); $i++) {
                    $handle[$data[$i]['name']] = $data[$i]['value'];
                }
                $handle['type'] = 2;
                $id = D('Alipays')->add($handle);
                echo $id;
                die;
            } else if ($type == 2) {
                $one = D('Alipays')->where(['id' => I('post.id')])->find();
                if (!empty($one)) {
                    ob_clean();
                    echo json_encode($one);
                    die;

                } else {
                    ob_clean();
                    echo json_encode(['info' => 0]);
                    die;
                }


            } else if ($type == 3) {
                $id = I('post.id');
                $data = $_POST['data'];
                $handle = array();
                for ($i = 0; $i < count($data); $i++) {
                    $handle[$data[$i]['name']] = $data[$i]['value'];
                }
                $id = D('Alipays')->where(['id' => $id])->save($handle);
                echo $id;
                die;

            } else if ($type == 4) {
                $id = D('Alipays')->where(['id' => I('post.id')])->delete();
                echo $id;
                die;
            } else if ($type == 5) {
                if (I('post.status') == 0) {
                    $id = D('Alipays')->where(['id' => I('post.id')])->save(['status' => 1, 'cause' => '']);
                    echo $id;
                    die;
                } else {
                    $id = D('Alipays')->where(['id' => I('post.id')])->save(['status' => 0, 'cause' => '手动下架']);
                    echo $id;
                    die;
                }


            }


        } else {

            $map = array(['type' => 2]);
            $list = $this->lists('Alipays', $map, $order);
            $this->assign('_list', $list);
            $this->meta_title = '提现支付宝';
            $this->display();

        }

    }


    public function set_alipay()
    {
        $this->meta_title = '支付宝配置';

        //当面付授权配置
        $list = M('shouquan')->select();
        $this->assign('huabeilist', $list);
        $this->display();

    }


    /**
     * 添加当面付授权
     *
     */
    public function addDangmianfuShouquan()
    {
        if (IS_POST) {
            $params = I('post.');
            $res = M('shouquan')->add($params);
            if ($res) {
                echo 1;
            } else {
                echo 0;
            }

        }
    }

    /**
     * 删除当面付授权
     */
    public function deleteDangmianfuShouquan()
    {
        $id = I('get.id');
        $res = M('shouquan')->where(['id' => $id])->delete();
        if ($res) {
            echo 1;
        } else {
            echo 0;
        }
    }

    /**
     * 测试手机网站支付分账功能是否正常
     */
//    public function testAlipay(){
//        $id = I('get.id');
//        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
//        $qrpay = new \Alipay;
//
//        $res = \Home\Logic\PayLogic::xyktest($id,$danhao,$qrpay);
//        if($res['code'] == 1){
//            echo json_encode([
//                'code' => 1,
//                'msg' => $res['msg'],
//                'data' => ''
//            ]);
//        }else{
//            echo json_encode([
//                'code' => 0,
//                'msg' => $res['msg'],
//                'data' => $res['data']
//            ]);
//
//        }
//    }

    public function add_user(){
        if(IS_POST){
            $code = I('post.code');
            $phone = I('post.phone');
            $find = M('ptyh')->where("account=$phone")->find();
//            $this->showError('',$find);
            if($find) $this->showError('该手机号码已注册');

//            if (empty($code)) {
//
//                $this->showError('请输入手机验证码');
//            } else {
//                $smsLogic = new \Common\Model\SmsLogic();
//                $smsResult = $smsLogic->checkCode($phone,$code,'register');
//
////                $smsResult['code'] = 1;
//                if($smsResult['code'] != 1)  $this->showError($smsResult['msg']);
//
//            }

            $tg_num = I('post.tg_num','');

            $data = I('post.');
            unset($data['code']);
//            unset($data['npassword']);

            $ptdata = D("Ptdata")->where(['id' => 1])->find();
            if ($tg_num == '') {
                // 一级
                $data['password'] = md5(I('post.password'));
                $data['pid'] = 0;
                $data['level'] = 1;
                $data['yh_uid'] = $this->getUserCode();
                $data['account'] = $phone;
                $data['status'] = 1;

            } else {
                //上级数据
                $py = D('Ptyh')->where(['tg_num' => $tg_num])->find();
                $data['password'] = md5(I('post.password'));
                $data['pid'] = $py['uid'];
                $data['yh_uid'] = $this->getUserCode();
                $data['account'] = $phone;
                $data['status'] = 1;

            }


            if ($tg_num == '') {

                $data['path1'] = $ptdata['pt_rate'];
                $up_set = $ptdata['pt_rate'];
                $up_set2 = $ptdata['pt_rate2'];
                $data2 = [
                    'money' => 0,
                    'count' => 0,
                    'status' => 1,
                    'up_set' => $up_set,
                    'up_set2' => $up_set2,
                    'path1' => $ptdata['pt_rate'],
                    'path2' => $ptdata['pt_rate2'],
                    'level' => $py['level'] + 1,
                ];

            } else {

                $gather = D('Gather')->where(['uid' => $py['uid']])->find(); //上级
                $up_set = $py['child_hb_rate'];
                $up_set2 = $py['child_xy_rate'];

                $data2 = [
                    'money' => 0,
                    'count' => 0,
                    'status' => 1,
                    'up_set' => $up_set,
                    'up_set2' => $up_set2,
                    'path1' => $ptdata['pt_rate'],
                    'path2' => $ptdata['pt_rate2'],
                    'level' => $py['level'] + 1,
                ];

            }


            $gather = M('Gather');

            $id2 = $gather->add($data2);
            if ($id2 > 0) {//gather存储成功再去存储用户信息

                $data['wx_uid'] = $this->wx_uid;
                $ptdata = M('ptdata')->where(['id' => 1])->find();
                //推广费率
                $data['child_hb_rate'] = ($up_set*100+$ptdata['hbtg']*100)/100;
                $data['child_xy_rate'] = ($up_set2*100+$ptdata['xyktg']*100)/100;
                $uid = D('Ptyh')->add($data);
                if ($uid > 0) {
                    $id = $gather->where(['id' => $id2])->save(['uid' => $uid]);

                    if(empty($py)){
                        $path= $uid;
                    }else{
                        $str_index = substr_count($py['path'],'/');
                        if( $str_index== 6){
                            $path = substr($py['path'],$str_index-1) . '/'.$uid;
                        }else{
                            $path=$py['path'] . '/' . $uid;
                        }




                    }
                    M('ptyh')->where(['uid' => $uid ])->save([
                        'tg_num' => \Home\Logic\UserLogic::buildEncodeReferralCode($uid),
                        'path' => $path
                    ]);
                    //增加上级的推广数量
                    \Home\Logic\UserLogic::addParentsTuiguangNum($uid);
//                    $this->showSuccess('注册成功');
//                    echo '注册成功';exit;
                    $this->success('注册成功',U('ptyh'));

                } else {
                    // 保存不成功不需要删除用户信息，提示再次上传即可
//                    $this->showError('注册失败，请稍后重试！');
                    echo '注册失败，请稍后重试！';exit;


                }
            } else {
//                $this->showError('注册失败，请稍后重试');
                echo '注册失败，请稍后重试';exit;


            }

        }else{

            $this->display();
        }
    }

    /**
     * 获取用户编码
     * @return string
     */
    private function getUserCode()
    {
        return date('md' . rand('000000', '999999'));
    }

    public function shangxiajia(){
        $id = I('id');
        $type = I('type');
//        echo json_encode(['id' => $id,'type' => $type]);exit;
        if($type == 2){
            //上架
            $use_status = 1;
        }else{
            $use_status = 0;
        }
        $result = M('kbsh')->where(['id' => $id])->save(['use_status' => $use_status]);
        if($result !== false){
            echo 1;exit;
        }else{
            echo 0;exit;
        }
    }

    /**
     * 异常订单列表
     */
    public function yichang(){
        $type = I('get.type');
        $map = array();
        $order = 'pay_time desc';
        if ($type == 'today') {
            $time1 = strtotime(date("Ymd"));
            $time2 = strtotime(date("Ymd", time() + 86400));
            $map['pay_time'] = array(array('gt', $time1), array('lt', $time2), 'and');

        }
        $map['status'] = array('in',[4,5,6]);


        $list = $this->lists('Dingdan', $map, $order);


        // $list   =   $this->lists('Dingdan','','pay_time desc','');
        $sum['total'] = D('Gather')->sum('money');
        $time1 = strtotime(date("Ymd", strtotime("+1 day")));
        $time2 = strtotime(date("Ymd"));
        $sum['td_in'] = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

        $sum['td_out'] = D('Extract')->where("status=1 and time between $time2 and $time1")->sum('money');
        $sum['divide'] = D('Dividend')->where("status=1")->sum('divide');
        $sum['t_money'] = D('Dingdan')->where("status=1")->sum('pay_money');
        foreach($list as $k => $v){
            $list[$k]['shop_name'] = M('kbsh')->where()->getField('name');
        }

        $this->assign('sum', $sum);
        $this->assign('_list', $list);
        $this->meta_title = '异常订单记录';
        $this->display();
    }

    /**
     * 追账
     */
    public function ajaxZhuizhang(){
        $id = I('id');
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $qrpay = new \Alipay;
        //状态:0=未支付,1=已支付,2=没分给平台,3=分给平台,4=没分给平台，分给客户,5=没分给平台，没分给客户，6=分给平台，没分给客户,7=分账成功
        //追账状态:0=待追账,1=追账成功,2=追账失败
        $dingdan = M('dingdan')->find($id);
        $toAccount = D('Adata')->where(['id' => 1])->find();//平台收款支付宝，用户提现

        if($dingdan['status'] == 4){
            $account = $dingdan['admin_money'];
        }elseif ($dingdan['status'] == 5){
            $account = ($dingdan['admin_money']*100 + $dingdan['user_money'])/100;
        }elseif ($dingdan['status'] == 6){
            $account = $dingdan['user_money'];
        }

        $royalty_parameters = [
            'trans_out' => "{$dingdan['serller_id']}",//分账出去的user_id 分账支出方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'trans_in' => $toAccount['t_account'], //合作伙伴id 分账收入方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'amount' => $account,   //分账出去的金额
            'desc' => '绿叶收银台服务中心-追账',
        ];
        $app_auth_token = '';
        $out_request_no = date("Ymd") . rand(1000000000, 9999999999);  //分账流水号

        if($dingdan['pay_type'] == 2){
            //当面付花呗
            $adata = M('kbsh')->where(['user_id' => $dingdan['seller_id']])->find();

        }else{
            $adata = M('alipays')->where(['pid' => $dingdan['seller_id']]);
        }

        $result = $qrpay->settle($out_request_no, $dingdan['trade_no'], $royalty_parameters, $app_auth_token, $adata);

        if ($result->trade_no == $dingdan['trade_no'] && empty($result->sub_msg)) {
            //修改追账状态
            M('dingdan')->where(['id' => $id])->save(['zhui_status' => 1]);
            echo json_encode(['code' => 1, 'msg' => '追账成功','data' => '']);

        } else {
            $sub_msg = $result->sub_msg;
            if ($sub_msg == '接口返回错误') {
                echo json_encode(['code' => 0, 'msg' => '追账失败','data' => $result->sub_msg]);
                M('dingdan')->where(['id' => $id])->save(['zhui_status' => 2]);


            } else {

            }
        }


    }

    /**
     * 一键提现
     */
    public function alltixian(){
        $where['yongjin'] = ['gt',0];
        $where['fenrun'] = ['gt',0];
        $where['_logic'] = 'or';
        $uids = M('gather')->where($where)->getField('uid',true);
        $payLogic = new \Admin\Logic\PayLogic();
        foreach ($uids as $k => $v){
            $payLogic->tixian($v);
        }

    }

    public function changepwd(){
        $password = I('password');
        $uid = I('uid');

        $res = M('ptyh')->where(['uid' => $uid])->save(['password' => md5($password)]);
        if($res !== false){
            echo json_encode(['code' => 1, 'msg' => '修改成功','data' => '']);
        }else{
            echo json_encode(['code' => 0, 'msg' => '修改失败','data' => '']);

        }
    }

    /**
     * 删除商户
     */
    public function del_kbsh(){
        $id = I('id');

        $res = D('Kbsh')->where("id=$id")->delete();


        if($res> 0){
            $redis = new \Predis\Client(C('REDIS'),['prefix' => C('REDIS_PREFIX')]);
            $rediskey = \Home\Logic\PayLogic::getRedisKeyByType(2);
            $redis->lrem($rediskey,1,$id);
            echo json_encode(['code' => 1, 'msg' => '']);
        }else{
            echo json_encode(['code' => 0, 'msg' => '']);

        }


    }






}